<template>
  <el-dialog v-model="dialogVisible" title="编辑分类信息" width="600px" draggable>
    <el-form :model="form" label-width="100px">
      <!-- Parent Category Name -->
      <el-form-item label="父分类名称">
        <el-input v-model="form.categoryParentName" autocomplete="off"/>
      </el-form-item>
      <!-- Child Category Name -->
      <el-form-item label="子分类名称">
        <el-input v-model="form.categoryChildName" autocomplete="off"/>
      </el-form-item>
      <!-- Category Image -->
      <el-form-item label="分类图片">
        <div v-if="isShowOld">
          <img class="pic" :src="form.categoryImg" alt=""/>
          <el-button type="primary" @click="updateImg">修改图片</el-button>
        </div>
        <div v-else>
          <upload ref="uploadComponent" @upload-success="handleUploadSuccess"></upload>
        </div>
      </el-form-item>
      <el-form-item label="规格ID">
        <el-input v-model="form.standards.standardId" autocomplete="off"/>
      </el-form-item>
      <!-- Standards -->
      <el-form-item label="化学成分">
        <el-input v-model="form.standards.chemicalComposition" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="内容描述">
        <el-input v-model="form.standards.content" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="纯度">
        <el-input v-model="form.standards.purity" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="性能">
        <el-input v-model="form.standards.performance" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="容量">
        <el-input-number v-model="form.standards.capacity" :min="0"/>
      </el-form-item>
      <el-form-item label="长度">
        <el-input-number v-model="form.standards.length" :min="0"/>
      </el-form-item>
      <el-form-item label="直径">
        <el-input-number v-model="form.standards.diameter" :min="0"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitEdit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {defineProps, defineEmits, ref, reactive, computed, watch} from 'vue';
import {ElMessage} from 'element-plus';
import {updateCategory} from '@/api/category';
import upload from '@/components/upload.vue';
import {headImgStore} from '@/store/tokenStore';
import {deleteFile} from "@/api/utils";

const headImg = headImgStore();

const props = defineProps({
  drawerVisible: Boolean,
  category: {
    type: Object as () => {
      categoryId: number;
      categoryParentName: string;
      categoryChildName: string;
      categoryImg: string;
      standards: {
        standardId: number;
        chemicalComposition: string;
        content: string;
        purity: string;
        performance: string;
        capacity: number;
        length: number;
        diameter: number;
      };
    },
    required: true,
  },
});

const emit = defineEmits(['update:drawerVisible', 'formSubmitted']);

const form = reactive({...props.category});

watch(
    () => props.category,
    (newVal) => {
      if (newVal) {
        Object.assign(form, newVal);
      }
    },
    {immediate: true, deep: true}
);

const dialogVisible = computed({
  get: () => props.drawerVisible,
  set: (value) => emit('update:drawerVisible', value),
});
const isShowOld = ref(true);
const uploadComponent = ref(null);

const updateImg = () => {
  isShowOld.value = false;
};

const handleUploadSuccess = (url) => {
  form.categoryImg = url;
};

const closeDialog = () => {
  dialogVisible.value = false;
};

const submitEdit = async () => {
  try {
    let tempImg = form.categoryImg;
    if (uploadComponent.value && !isShowOld.value) {
      // 使用Promise等待上传完成
      const uploadPromise = new Promise<void>((resolve, reject) => {
        let unwatch: (() => void) | null = null; // 提前声明unwatch
        unwatch = watch(
            () => headImg.headImg,
            (newVal) => {
              if (newVal) {
                if (unwatch) unwatch(); // 确保unwatch已初始化
                resolve();
              }
            },
            {immediate: true}
        );

        // 调用子组件的manualUpload方法并立即启动上传
        uploadComponent.value.manualUpload();
      });

      await uploadPromise; // 等待上传完成
    }
    if (headImg.headImg !== '') {
      form.categoryImg = headImg.headImg;
    } else {
      form.categoryImg = tempImg;
    }
    // console.log(form)
    const sendForm = {
      categoryParentName: form.categoryParentName,
      categoryChildName: form.categoryChildName,
      categoryImg: form.categoryImg,
      standardId: parseInt(form.standards.standardId),
      standardsUpdateDTO: {
        chemicalComposition: form.standards.chemicalComposition,
        content: form.standards.content,
        purity: form.standards.purity,
        performance: form.standards.performance,
        capacity: parseInt(form.standards.capacity),
        length: parseInt(form.standards.length),
        diameter: parseInt(form.standards.diameter)
      }
    };
    // console.log(sendForm)
    await updateCategory(sendForm, form.categoryId);
    closeDialog();
    emit('formSubmitted');
    deleteImg(tempImg)
    isShowOld.value = true;
    headImg.clearHeadImg()
  } catch (error) {
    ElMessage.error('更新失败，请检查输入信息或网络连接');
    console.error(error);
  }
};
const deleteImg = async (tempImg) => {
  let fileName = tempImg.split('/').pop();
  if (fileName) {
    const res = await deleteFile(fileName);
    console.log(res);
  }
}
</script>

<style scoped>
.pic {
  width: 100px;
  height: 100px;
}

.dialog-footer {
  text-align: right;
}
</style>
